import { createRouter, createWebHistory } from 'vue-router'
import {useAuthStore} from '../store'

// 布局组件
import Layout from '../layouts/MainLayout.vue'

// 页面组件
const Login = () => import('../pages/auth/Login.vue')
const Dashboard = () => import('../pages/dashboard/Index.vue')
// const Users = () => import('../pages/system/Users.vue')
// const Roles = () => import('../pages/system/Roles.vue')
// const Menus = () => import('../pages/system/Menus.vue')
// const NotFound = () => import('../pages/errors/404.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: "/",
    component: Layout,
    meta: { requiresAuth: true },
    children:[
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '仪表板' }
      },
      // {
      //   path: '/system/users',
      //   name: 'Users',
      //   component: Users,
      //   meta: { title: '用户管理' }
      // },
      // {
      //   path: '/system/roles',
      //   name: 'Roles',
      //   component: Roles,
      //   meta: { title: '角色管理' }
      // },
      // {
      //   path: '/system/menus',
      //   name: 'Menus',
      //   component: Menus,
      //   meta: { title: '菜单管理' }
      // }
    ]
  },
  // {
  //   path: '/:pathMath(.*)*',
  //   name: 'NotFound',
  //   component: NotFound
  // }
]

const router = createRouter({
 /*
    使用HTML5 History模式，不带#的URL
    import.meta.env.BASE_URL:获取环境变量中的基础路径
    routers：使用之前定 义的路由配置数组routers作为路由规则传入
  */
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore() // 正确实例化

  // 从localStorage和store双重验证
  const isAuthenticated =
    authStore.isAuthenticated ||
    !!localStorage.getItem('access_token')

  // 登录状态同步逻辑
  if (!authStore.isAuthenticated && localStorage.getItem('access_token')) {
    try {
      // 如果有token但store未初始化，这里可以添加用户信息获取逻辑
      // await authStore.fetchUser()
    } catch (e) {
      localStorage.removeItem('access_token')
    }
  }

  // 路由控制逻辑
  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.name === 'Login' && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
